package com.qa.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qa.pojo.History;
import com.qa.pojo.Users;
import com.qa.service.IHisService;
import com.qa.util.JsonFormatTool;

@Controller
@RequestMapping("/his")
public class HisController {
	@Resource
	private IHisService hisService;

	JsonFormatTool jsonFormatTool = new JsonFormatTool();
	List<History> his = new ArrayList<History>();
	Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 通过usersID查询请求历史记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/selectHis")
	@ResponseBody
	public Map<String, Object> selectHis(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			his = this.hisService.getHistoryById(usersid);
			if (his.size() == 0) {
				resultMap.put("tag", "error");
			} else {
				resultMap.put("tag", "success");
				resultMap.put("result", his);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 将查询记录插入到数据库中
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/insertHis", method = RequestMethod.POST)
	@ResponseBody
	public boolean insertHis(HttpServletRequest request,
			HttpServletResponse response) {
		response.setStatus(200);
		History his = new History();
		try {

			his.setMethodtype(request.getParameter("Methodtype"));
			his.setUrl(URLDecoder.decode(request.getParameter("urlStr")
					.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8"));
			his.setUsersid(Integer.valueOf(request.getParameter("usersid")));
			// 根据传过来的值选择两种方式的任一种，目前不知道规律
			/*
			 * his.setResult(new
			 * String(request.getParameter("result").toString()
			 * .getBytes("iso8859_1"), "utf-8"));
			 */
			his.setResult(URLDecoder.decode(request.getParameter("result")
					.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8"));
			his.setTime(new Timestamp((new Date()).getTime()));
			his.setParams(new String(request.getParameter("params").toString()
					.getBytes("iso8859_1"), "utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return this.hisService.insertHistory(his);

	}

	/**
	 * 通过hisid删除历史记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/deleteHis", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteHis(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int hisId = Integer.valueOf(request.getParameter("hisId"));
			int isDelete = this.hisService.deleteHistoryByHisId(hisId);
			if (isDelete == 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 对指定his进行标识
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/signHis", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> signHis(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {

			ArrayList<Integer> hisList = new ArrayList<Integer>();
			List<String> hisListString = Arrays.asList(URLDecoder.decode(
					request.getParameter("signGroup"), "UTF-8"));
			String[] hisList2 = hisListString.get(0).split(",");
			for (String a : hisList2) {
				hisList.add(Integer.valueOf(a));
			}
			String signText = URLDecoder.decode(
					request.getParameter("signText"), "UTF-8");
			int isUpdate = this.hisService.UpdateHisSign(hisList, signText);
			if (isUpdate > 0) {
				resultMap.put("tag", "success");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 删除当前用户下所有历史查询记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/deleteAll", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteAll(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int usersid = Integer.valueOf(((Users) request.getSession()
					.getAttribute("user")).getUsersid());
			int isDelete = this.hisService.deleteByUsersId(usersid);
			if (isDelete >= 0) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}
}